<?php
/**
 * Created by JetBrains PhpStorm.
 * User: heimuya
 * Date: 13-8-14
 * Time: 下午5:14
 * 系统后台登录控制类
 */
class LoginAction extends Action{
    public function index($type = null){
    	if(session('unick') && session('uid')){
            $this->redirect('Index/index');
        }
        //登陆首页
        $type = $this->_get('type');
        switch($type){
            case 1:
                $errorMsg = L('infoEmpty');
                break;
            case 2:
                $errorMsg = L('infoError');
                break;
            case 3:
                $errorMsg = L('unLogin');
                break;
            case 4:
                $errorMsg = L('unvalid');
                break;
            default:
                $errorMsg = '';
                break;
        }
        $this->assign('errorMsg', $errorMsg);
        $this->display();
    }

    /**
     * 登陆判断
     */
    public function doLogin(){
        $postData = $this->_post();
        if(!$postData['username'] || !$postData['password']){//用户名或者密码为空
            $this->redirect('Login/index', array('type' => 1));
        }
        $user = D('User');
        if(!($userInfo = $user->getUserInfo($postData['username'])) || $userInfo['password'] != md5($postData['password'])){//用户名或者密码错误
            $this->redirect('Login/index', array('type' => 2));
        }
		//判断登陆用户的状态是否可用
		if($userInfo['valid'] !== 'y' || $userInfo['usertype'] !== 'admin'){
			$this->redirect('Login/index', array('type' => 4));
		}
        //设置cookie
        unset($userInfo['password']);
        setCookieInfo($userInfo, 'uInfo');
		
        $sessionData = array(
            'uid'           => $userInfo['id'],
            'unick'         => $userInfo['usernick'],
            'utype'         => $userInfo['usertype'],
            'uname'    	  	=> $userInfo['username'],
            'csstype'		=> $userInfo['csstype']
        );
        setSession($sessionData);//设置session数据
		
		//设置用户登陆信息
		$loginInfo = array(
			'last_ip'		=> get_client_ip(),
			'last_login'	=> time(),
			'status'		=> 'online'
		);
		$user->setUserInfo($loginInfo, $userInfo['id']);
		
        $this->redirect('Index/index');//跳转到后台管理首页
    }


    /**
     * 退出登录
     */
    public function logout(){
    	//设置用户退出登陆信息
		$loginInfo = array(
			'status'		=> 'offline'
		);
		D('User')->setUserInfo($loginInfo, session('uid'));
        cookie(null);
        session_destroy();
        $this->redirect('Login/index');
    }
}